package common.pojo;

import java.util.HashMap;

/**
 * Created by luozongsheng on 20/12/16.
 */
public class CommonResult<T> extends HashMap {

    public static final int SUCCESS = 0;

    public static final int FAILS = 1;

    public static final int SERVER_ERROR = -1;

    private int code;

    private String message;

    private T data;

    private Object transientData;

    public CommonResult() {
        this.code = CommonResult.FAILS;
        this.put("code",this.code);
    }

    public CommonResult(int code, String message) {
        this.code = code;
        this.message=message;
        this.put("code",this.code);
        this.put("message",this.message);
    }

    public int getCode() {
        return (Integer)this.get("code");
    }

    public CommonResult setCode(int code) {
        this.code = code;
        this.put("code",this.code);
        return this;
    }

    public String getMessage() {
        return (String)this.get("message");
    }

    public CommonResult setMessage(String message) {
        this.message = message;
        this.put("message",this.message);
        return this;
    }

    public Object getData() {
        return this.get("data");
    }

    public CommonResult setData(T data) {
        this.data = data;
        this.put("data",this.data);
        return this;
    }

    public boolean isSuccess(){
        return this.getCode()==SUCCESS;
    }

    public boolean isNotSuccess(){
        return !isSuccess();
    }

    public Object getTransientData() {
        return transientData;
    }

    public CommonResult setTransientData(Object transientData) {
        this.transientData = transientData;
        return this;
    }

    public static CommonResult returnDataWrapper(Object... obj) {
        return returnSuccessWrapper(obj);
    }


    public static CommonResult returnWrapper(int code, String message, Object... obj) {
        CommonResult result = new CommonResult();
        result.setMessage(message);
        if(obj != null && obj.length != 0) {
            if(obj.length == 1) {
                result.setData(obj[0]);
            } else {
                result.setData(obj);
            }
        } else {
            result.setData(null);
        }
        result.setCode(code);
        return result;
    }

    public static CommonResult returnBoolWrapper(boolean bool, String fails, Object... obj) {
        if (bool) {
            return returnSuccessWrapper(obj);
        }
        return returnFailsWrapper(fails, obj);
    }

    public static CommonResult returnSuccessWrapper(Object... obj) {
        return returnWrapper(CommonResult.SUCCESS, "success", obj);
    }

    public static CommonResult returnFailsWrapper(String message, Object... obj) {
        return returnWrapper(CommonResult.FAILS, message, obj);
    }
}
